<?php
set_time_limit(0);
ini_set('memory_limit', '1500M');
Yii::import('application.mlm.core.mlm_function');
Yii::import('application.mlm.core.binary.bonus.bonus_gen_node_products');
Yii::import('application.mlm.core.mlm_lib_gi');
Yii::import('application.mlm.core.binary.*');
Yii::import('application.mlm.core.matrix.*');
Yii::import('application.mlm.core.board.*');
class RegistrasiController extends Controller {
    private $network_id_arr = array();
//    public function actionIndex() {
//        if (isset($_POST['otomatis'])) {
//            $this->step1_otomatis($_POST['sponsor_auto']);
//        } else {
//            $this->step1_manual($_POST['sponsor'], $_POST['manual']);
//        }
//
//        $this->pageTitle = "Registrasi Langkah Ke Satu";
//        //buat ajax YII
//        Yii::app()->clientScript->registerScript('ajax', "$(\"input[name='sponsor_auto'],input[name='upline'],input[name='sponsor']\").bind('keyup change'
//                                               ,function(){
//                                               var tulis = $(this).next();
//                                                var network_mid= $(this).val();
//                                                if(network_mid !== \"\")
//                                                {
//                                                    $(this).next().fadeIn('slow',function(){
//                                                        tulis.html('loading');
//                                                    });
//                                                    $.ajax({
//                                                            type: \"POST\",
//                                                            data: \"ajax_request=\"+network_mid,
//                                                            url:  \"{$this->createUrl("registrasi/ajax_request")}\",
//                                                            success: function(response){
//                                                            tulis.html(response);
//                                                                },
//                                                            dataType:\"html\"
//                                                            });
//                                                    return false;
//                                                }
//                                                else tulis.html(\"\");
//                                            });", CClientScript::POS_READY);
//        $this->render('index');
//    }
    /**
     * Buat INdex yang dijadikan cuman satu step
     */
    public function actionIndex() {
        $show = TRUE;
        $message = "";
        $model = new registrasi_form('registrasi');
        /**
         * Buat Ajax
         */
        $this->pageTitle = "Registrasi ".Yii::app()->name;
        //buat ajax YII
        Yii::app()->clientScript->registerScript('ajax', "$(\"#".CHtml::activeId($model, 'member_sponsor').",#".CHtml::activeId($model, 'member_upline')."\").bind('keyup change'
                                               ,function(){
                                               var tulis = $(this).next();
                                                var network_mid= $(this).val();
                                                if(network_mid !== \"\")
                                                {
                                                    $(this).next().fadeIn('slow',function(){
                                                        tulis.html('loading');
                                                    });
                                                    $.ajax({
                                                            type: \"POST\",
                                                            data: \"ajax_request=\"+network_mid,
                                                            url:  \"{$this->createUrl("registrasi/ajax_request")}\",
                                                            success: function(response){
                                                            tulis.html(response);
                                                                },
                                                            dataType:\"html\"
                                                            });
                                                    return false;
                                                }
                                                else tulis.html(\"\");
                                            });", CClientScript::POS_READY);
        if (isset($_POST['registrasi_form'])) {
            //set attributnya
           
            $model->setAttributes($_POST['registrasi_form'], false);
           
            if ($model->validate()) {

                //ambil data yang ada di attribut
                //network nya
                $arr_network['sponsor_mid'] = $model->member_sponsor;
                $arr_network['upline_mid'] = $model->member_upline;
                $arr_network['position'] = $model->position;
                //serial nya
                $arr_card['serial_id'] = $model->serial_id;
                $arr_card['serial_mid'] = '';
                $arr_card['serial_pin'] = $model->serial_pin;
                //data membernya
                //$arr_member['register_id'] = $model['register_id'];
                $arr_member['password'] = md5($model->password);
                $arr_member['member_nickname'] = $model->member_nickname;
                $arr_member['member_name'] = $model->member_name;
                $arr_member['member_email'] = $model->member_email;
                $arr_member['member_phone'] = $model->member_phone;
                $arr_member['member_mobilephone'] = $model->member_mobilephone;

                
                /*
                 * BANK 
                 */
                $arr_member['member_bank_account_name'] = $model->member_name;
                $arr_member['member_bank_id'] = $model->member_bank_id;
                $arr_member['member_bank_city'] = $model->member_bank_city;
                $arr_member['member_bank_branch'] = $model->member_bank_branch;
                $arr_member['member_bank_account_no'] = $model->member_bank_account_no;
                
//                echo '<pre>';
//                print_r($arr_member);
//                echo '</pre>';
//                exit;
                //saatnya registrasi
                $mlm = new mlm_lib_gi();
                //data array buat bonus distributor
                $bonus_arr = array('sponsor', 'sponsor_upgrade', 'match', 'gen_node', 'gen_node_extra','gen_node_extra_warehouse', 'gen_node_products', 'gen_match','extra_sponsor','royalti_angsuran');
                $mlm->set_bonus($bonus_arr)
                     ->set_date(date("Y-m-d"))
                     ->set_hu(7);
                $mlm->set_data_serial($arr_card)
                        ->set_data_member($arr_member)
                        ->set_data_network($arr_network);
                $member_network_id = $mlm->get_network_id_arr();
                $network_mid = function_lib::get_network_mid($member_network_id[1]);
                $network_id = $member_network_id[1];
                $sponsor = new mlm_sponsor;
                $sponsor->set_date(date("Y-m-d"))->gen_node(function_lib::get_network_id($model->member_sponsor));



                //sekarang buat bonus pasangan
                $match = new mlm_match;
                $match->set_date(date("Y-m-d"));
                $match->execute();
                //buat jaringan matrixnya
                $mlm_matrix = new mlm_matrix;
                $mlm_matrix->set_date(date("Y-m-d"))->set_height(10)->set_width(4)->set_network_id($network_id)->set_network_mid($network_mid)->insert_node();
//                $matrix = new mlm_matrix();
//                $mlm_matrix->set_date(date("Y-m-d"))
//                               ->set_height(10)
//                               ->set_width(4)
//                              ->set_network_id($network_id)->set_network_mid($network_mid)->insert_node();
                //ambil pesannya
                //generasi produknya
//                $bonus_gen_product = new bonus_gen_node_products;
//                $bonus_gen_product->set_date(date("Y-m-d"))
//                                  ->set_sponsor_network_id(function_lib::get_network_id($model->member_sponsor))
//                                  ->set_network_level_status('distributor')
//                                  ->set_level(10)
//                                  ->execute();
                $message = $mlm->get_message();
                $show = FALSE;
            }
        }
        $this->render('step2', array('model' => $model, 'show' => $show, 'message' => $message));
    }

    public function step1_otomatis($sponsor) {
        $mlm_function = new mlm_function;
        $RegId = "S" . substr($sponsor, 6, 2) . date("dmyHms");
        $network_id = function_lib::get_network_id($sponsor);
        if ($network_id) {
            $node_left = explode(" ", $mlm_function->get_last_node($network_id, 'left'));
            $node_right = explode(" ", $mlm_function->get_last_node($network_id, 'right'));
            if ($node_left[1] > $node_right[1]) {
                $upline_mid = $node_right[0];
                $position = "R";
                $position_text = "Kanan";
            } else {
                $upline_mid = $node_left[0];
                $position = "L";
                $position_text = "Kiri";
            }
            //masukkan hasil dari perbandingan ke session
            Yii::app()->session['reg'] = array('sponsor_mid' => $sponsor,
                'upline_mid' => function_lib::get_network_mid($upline_mid),
                'position' => $position,
                'position_text' => $position_text);
            $this->redirect(array("step2"));
        } else {
            Yii::app()->user->setFlash('error', "Sponsor Tidak ada atau Masih kosong!!");
            $this->refresh();
        }
    }

    public function actionManual() {
        $sponsor = new mlm_sponsor;
        $sponsor->set_sponsor("ESD10000030")
                ->add_sponsor_depend('gen')
                ->set_date(date("Y-m-d"))
                ->execute();
    }

    // Uncomment the following methods and override them if needed
    /*
      public function filters()
      {
      // return the filter configuration for this controller, e.g.:
      return array(
      'inlineFilterName',
      array(
      'class'=>'path.to.FilterClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }

      public function actions()
      {
      // return external action classes, e.g.:
      return array(
      'action1'=>'path.to.ActionClass',
      'action2'=>array(
      'class'=>'path.to.AnotherActionClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }
     */

    /**
     * Method Step2 dari registrasi
     */
    public function actionStep2() {
        $show = TRUE;
        $message = "";
        //jika ada sessionnya saja
        if (isset(Yii::app()->session['reg'])) {
            $model = new registrasi_form();
            if (isset($_POST['registrasi_form'])) {
                //set attributnya
                $model->setAttributes($_POST['registrasi_form'], false);
                if ($model->validate()) {

                    //ambil data yang ada di attribut
                    //network nya
                    $arr_network['sponsor_mid'] = $model->sponsor_mid;
                    $arr_network['upline_mid'] = $model->upline_mid;
                    $arr_network['position'] = $model->position;
                    //serial nya
                    $arr_card['serial_id'] = $model->serial_id;
                    $arr_card['serial_pin'] = $model->serial_pin;
                    //data membernya
                    //$arr_member['register_id'] = $model['register_id'];
                    $arr_member['password'] = md5($model->password);
                    $arr_member['member_name'] = $model->member_name;
                    $arr_member['member_email'] = $model->member_email;
                    $arr_member['member_sex'] = $model->member_sex;
                    $arr_member['member_address'] = $model->member_address;
                    $arr_member['member_city_id'] = $model->member_city_id;
                    $arr_member['member_state_id'] = $model->member_state_id;
                    //$arr_member['member_country_id'] = $session['member_country_id'];
                    $arr_member['member_country_id'] = 102; //indonesia
                    $arr_member['member_zipcode'] = $model->member_zipcode;
                    $arr_member['member_birth_place'] = $model->member_birth_place;
                    $arr_member['member_birth_date'] = $model->member_birth_date;
                    $arr_member['member_identity_type'] = $model->member_identity_type;
                    $arr_member['member_identity_no'] = $model->member_identity_no;
                    $arr_member['member_phone'] = $model->member_phone;
                    $arr_member['member_mobilephone'] = $model->member_mobilephone;
                    $arr_member['member_devisor_name'] = $model->member_devisor_name;
                    $arr_member['member_devisor_relationship'] = $mode->member_devisor_relationship;
                    $arr_member['member_devisor_phone'] = $model->member_devisor_phone;
                    $arr_member['member_bank_id'] = $model->member_bank_id;
                    $arr_member['member_bank_city'] = $model->member_bank_city;
                    $arr_member['member_bank_branch'] = $model->member_bank_branch;
                    $arr_member['member_bank_account_name'] = $model->member_bank_account_name;
                    $arr_member['member_bank_account_no'] = $model->member_bank_account_no;
                    //Proses Penginputan MLM dimulai
                    //saatnya registrasi
                    $mlm = new mlm_lib;
                    $mlm->add_titik_depend("node");
                    //set bonus sponsornya
                    $sponsor = new mlm_sponsor;
                    $sponsor->set_sponsor($arr_network['sponsor_mid'])->set_date(date("Y-m-d"))->execute();

                    $mlm->set_date(date("Y-m-d"));
                    $mlm->set_data_network($arr_network);
                    $mlm->set_data_serial($arr_card);
                    $mlm->set_data_member($arr_member);

                    //settting bonusnya
                    $mlm->set_bonus_titik(21, TRUE);
                    $mlm->insert_member();
                    //sekarang buat bonus pasangan
                    $match = new mlm_match;
                    $match->set_date(date("Y-m-d"));
                    $match->set_flushout(12);
                    $match->set_match_bool(TRUE);
                    $match->execute();
                    //ambil pesannya
                    $message = $mlm->get_message();
                    $show = FALSE;
                    unset(Yii::app()->session['reg']);
                }
            }

            $this->render('step2', array('model' => $model, 'show' => $show, 'message' => $message));
        }
        else
            $this->redirect(array("/registrasi"));
    }

    public function actionGet_area_name() {
        $area_id = $_POST['area_id'];
        $array_area = Yii::app()->db->createCommand()->from("ref_area")->where("area_par_id = '{$area_id}'")->queryAll();
        $data = CHtml::listData($array_area, 'area_id', 'area_name');
        foreach ($data as $area_id => $area_name) {
            echo CHtml::tag('option', array('value' => $area_id), CHtml::encode($area_name), true);
        }
    }

    public function actionajax_request() {

        $member = sys_network::model()->with('rel_network_to_member')->find(array('select' => '*',
                    'condition' => 'network_mid=:network_mid',
                    'params' => array(':network_mid' => $_POST['ajax_request']),
                ));
        //var_dump($member);
        if (empty($member)) {
            echo "member tidak ditemukan";
        } else {
            $member_name = $member->rel_network_to_member;
            echo $member_name->member_name . "<br />" . function_lib::get_area_name($member_name->member_city_id);
        }
    }
    public function actionBoard() {
        //var_dump(Yii::app()->params['bonus']['matrix_node']);
        Yii::import('application.mlm.core.board.mlm_board');
        $board = new mlm_board;
        //masukkan dulu member ke sys_network
        for($x = 1;$x <= 16;$x++) {
            $new_mid = $board->generate_mid($x, '1');
            Yii::app()->db->createCommand("INSERT INTO sys_board_network SET board_network_member_id = '".$x."',
                                                                                board_network_network_mid = '".$new_mid."',
                                                                                board_network_board_class = '1'")->execute();
            $manager_network_id = Yii::app()->db->getLastInsertID();
            $board->input_board($manager_network_id, date("Y-m-d"), '1');
        }
    }
    public function actionRekap() {
        $mlm = new mlm_node_gi();
        $mlm_matrix = new mlm_matrix();
        $sponsor = new mlm_sponsor;
        $sponsor->add_sponsor_depend('gen_node_extra');
        $match = new mlm_match;
        $match->set_match_bool(TRUE);
        $match_bonus = new mlm_match_gi();
        $match_bonus->add_pasangan_depend('gen_match');
        $match_bonus->add_pasangan_depend('match');
        $match_bonus->set_flushout(12);
        $board = new mlm_board;
        $network = sys_network::model()->with('rel_network_to_member')
                                       ->findAll(array('select' => '*',
                                                       'order' => 'network_id',
                                                       /*'condition' => 'network_id<=:network_id',
                                                       'params' => array(':network_id' => '200')*/));
        foreach($network as $row) {
            $tanggal = date("Y-m-d", strtotime($row->rel_network_to_member->member_join_datetime));
            $sponsor_mid = function_lib::get_network_mid($row->network_sponsor_network_id);
            $match->set_date($tanggal);
                switch($row->network_level_status) {
                case 'passive' :
//                    $mlm->set_status($row->network_level_status)->update_node($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match->execute();
                break;
                case 'distributor' :
//                    $sponsor->set_date($tanggal)->gen_node($row->network_sponsor_network_id);
//                    $mlm->set_status($row->network_level_status)->update_node($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match->execute();
//                    $mlm_matrix->set_date($tanggal)
//                               ->set_height(10)
//                               ->set_width(4)
//                              ->set_network_id($row->network_id)->set_network_mid($row->network_mid)->insert_node();
                break;
                case 'warehouse' :
//                    $sponsor->set_date($tanggal)->gen_node($row->network_sponsor_network_id);
//                    $mlm->set_status($row->network_level_status)->update_node($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match->execute();
//                    $mlm_matrix->set_date($tanggal)
//                              ->set_height(10)
//                              ->set_width(4)
//                               ->set_network_id($row->network_id)->set_network_mid($row->network_mid)->insert_node();
//                    $match_bonus->set_date($tanggal)->set_flushout(12);
//                    $match_bonus->insert_netgrow_bonus($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match_bonus->execute();
                break;
                case 'factory' :
//                    $sponsor->set_sponsor($sponsor_mid)->set_date($tanggal)->execute();
//                    $sponsor->set_date($tanggal)->gen_node($row->network_sponsor_network_id);
//                    $mlm->set_status($row->network_level_status)->update_node($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match->execute();
//                    $mlm_matrix->set_date($tanggal)
//                               ->set_height(10)
//                               ->set_width(4)
//                              ->set_network_id($row->network_id)->set_network_mid($row->network_mid)->insert_node();
//                    //board
                     $new_mid = $board->generate_mid($row->network_id, '1');
                    Yii::app()->db->createCommand("INSERT INTO sys_board_network SET board_network_member_id = '".$row->network_id."',
                                                                                        board_network_network_mid = '".$new_mid."',
                                                                                        board_network_board_class = '1'")->execute();
                    $manager_network_id = Yii::app()->db->getLastInsertID();
                    $board->input_board($manager_network_id, $tanggal, '1');
//                    $match_bonus->set_date($tanggal)->set_flushout(12);
//                    $match_bonus->insert_netgrow_bonus($row->network_id, $row->network_upline_network_id, $tanggal, 1);
//                    $match_bonus->execute();
                break;
            }
            //$match->execute();
        }
    }
    public function actionCron() {
        Yii::import('application.commands.bonus.cron_bonus');
        $yesterday = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
         $start_date = '2011-09-21';
        $cron_bonus = new cron_bonus;
        $data_arr = array('sponsor', 'match', 'gen_node', 'gen_node_extra', 'gen_match', 'matrix_node', 'board_fly', 'board_level');
        while (strtotime($start_date) <= strtotime($yesterday)) {
            //data array berisi nama class yang akan dipakai bonus
            foreach ($data_arr as $bonus_name) {
                $cron_bonus->set_bonus_name($bonus_name);
                $cron_bonus->set_date($yesterday);
                $string_bonus = strval($bonus_name);
                preg_match("/gen/", $string_bonus, $matcg);
                preg_match("/board/", $string_bonus, $match_board);
                preg_match("/matrix/", $string_bonus, $match_matrix);
                if (!empty($matcg)) {
                    $cron_bonus->execute_generation();
                } elseif (!empty($match_board)) {
                    $cron_bonus->execute_board();
                } elseif (!empty($match_matrix)) {
                    $cron_bonus->execute_matrix();
                } else {
                    $cron_bonus->execute();
                }
            }
            $start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));
        }
    }
}